package com.xbdun.web.validatebmp.upload.core.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.alibaba.fastjson.JSON;
import com.xbdun.common.api.XbdUnObjectResult;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.util.CodeUtil;
import com.xbdun.facade.validatebmp.constant.WatermarkPostion;
import com.xbdun.facade.validatebmp.upload.core.AllowUploadType;
import com.xbdun.facade.validatebmp.upload.core.UploadVo;
import com.xbdun.web.validatebmp.upload.core.UpLoadUtil;
import com.xbdun.web.validatebmp.upload.core.UploadFile;
import com.xbdun.web.validatebmp.upload.core.UploadTypeUtil;
/**
 * 文件上传开放接口控制器
 */
public class UploadOpenController extends AbstractController {
	private static final String param_id="id";
	private static final String param_watermark="watermark";
	private static Log log=LogFactory.getLog(UploadOpenController.class);
	//处理上传业务接口
	private UploadOpenService uploadOpenService;
	//Session Key,如果不配置将不会验证Session
	private String sessionKey;
	//自定义类别Id
	private Integer id;
	//水印位置
	private WatermarkPostion watermarkPostion;
	//API客户端编号
	private String apiClientNo;
	private List<AllowUploadType> allowUploadTypeList= new ArrayList<AllowUploadType>(); 
	public UploadOpenController() {}
	@PostConstruct
	public void initAllowUploadType(){
		//类型指针的引用
		UploadTypeUtil.setListUploadType(allowUploadTypeList);
	}
	public ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception {
		log.debug(request.getRequestURL().toString());
		XbdUnObjectResult result=checkFileRequest(request);
		try {
			String upfmt = request.getParameter("upfmt");//希望返回的图片
			if(result.getSuccess()){
				String pic = request.getParameter("pic1");
				List<UploadVo> voList=new ArrayList<UploadVo>();
				//增加flash头像裁剪功能参数判断,头像裁剪上传流程
				if(!StringUtils.isEmpty(pic)){
					@SuppressWarnings("unchecked")
					Map<String, Object> map = (Map<String, Object>)result.getData();
					UploadVo vo=uploadOpenService.upload(upfmt,getWatermarkPostion(request),apiClientNo,(UploadFile)map.get("file"), (InputStream)map.get("pic"));
					if(null!=vo){
						log.debug("upload file:"+vo);
						voList.add(vo);
					}
				}else{//正常上传流程
					@SuppressWarnings("unchecked")
					List<UploadFile> listFile=(List<UploadFile>)result.getData();
					for(UploadFile upFile:listFile){
						UploadVo vo=uploadOpenService.upload(upfmt,getWatermarkPostion(request),apiClientNo,upFile, upFile.getInputStream());
						if(null!=vo){
							log.debug("upload file:"+vo);
							voList.add(vo);
						}
					}
				}
				result.setData(voList);
			}else{
				result.setData(null);
			}
		} catch (Exception e) {
			log.error("upload",e);
			result.setBizException(e);
			result.setData(null);
		}
		log.debug(result);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(JSON.toJSON(result));
		return null;
	}
	/**
	 * 获取水印位置
	 * @param request {@link AllowUploadType}
	 * @return {@link WatermarkPostion}
	 */
	private WatermarkPostion getWatermarkPostion(HttpServletRequest request){
		if(this.watermarkPostion!=null){
			return this.watermarkPostion;
		}
		String wk=request.getParameter(param_watermark);
		if(null!=wk){
			try {
				int key=Integer.parseInt(wk);
				return WatermarkPostion.valueOf(key);
			} catch (Exception e) {
				log.error("getWatermarkPostion:"+wk);
			}
		}
		return WatermarkPostion.NONE;
	}
	/**
	 * 检查请求
	 * @param request {@link AllowUploadType}
	 * @return {@link XbdUnObjectResult}
	 */
	private XbdUnObjectResult checkFileRequest(HttpServletRequest request){
		XbdUnObjectResult result= XbdUnObjectResult.newInstance();
		result.setBizException(BizException.SUCCESS);
		if(!StringUtils.isEmpty(sessionKey)){
			if(null==request.getSession().getAttribute(sessionKey)){
				result.setBizException(BizException.POWER_FAIL);
				return result;
			}
		}
		int myTypeId=0;
		if(id==null || id<0){
			String requestId=request.getParameter(param_id);
			if(StringUtils.isEmpty(requestId)){
				result.setBizException(BizException.PARAM_CHKE_FAIL);
				return result;
			}
			myTypeId=Integer.parseInt(requestId);
		}else{
			myTypeId=id;
		}
		AllowUploadType allowUploadType=UploadTypeUtil.getAllowUploadType(myTypeId);
		if(null==allowUploadType){
			return (XbdUnObjectResult) XbdUnObjectResult.newInstance().setBizException(BizException.PARAM_CHKE_FAIL);
		}
		String pic = request.getParameter("pic1");
		//增加flash头像裁剪功能参数判断,头像裁剪上传流程（图片文件为base64字符串）
		if(!StringUtils.isEmpty(pic)){
			try {
				Map<String, Object> map = new HashMap<String, Object>();
				UploadFile uploadFile=new UploadFile(null ,allowUploadType);
				map.put("file", uploadFile);
				InputStream imput = CodeUtil.getInputStreamFormBASE64Str(pic);
				map.put("pic",imput );
				result.setData(map);
			} catch (IOException e) {
				log.error("checkRequest 获取头像BASE64 错误:", e);
			}
		}else{//正常上传流程
			MultipartHttpServletRequest multpartRequest=(MultipartHttpServletRequest)request;
			Map<String,MultipartFile> fileMap= multpartRequest.getFileMap();
			Iterator<String> keyIt=fileMap.keySet().iterator();
			List<UploadFile> listFile=new ArrayList<UploadFile>();
			while(keyIt.hasNext()){
				String key=keyIt.next();
				log.info("key:"+key);
				MultipartFile file=fileMap.get(key);
				UploadFile uploadFile=new UploadFile(file, allowUploadType);
				UpLoadUtil.checkUploadFile(result,uploadFile);
				if(!result.getSuccess()){
					return result;
				}
				listFile.add(uploadFile);
			}
			result.setData(listFile);
			return result;
		}
		return result;
	}
	
	public String getSessionKey() {
		return sessionKey;
	}
	public void setSessionKey(String sessionKey) {
		this.sessionKey = sessionKey;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public List<AllowUploadType> getAllowUploadTypeList() {
		return allowUploadTypeList;
	}
	public void setAllowUploadTypeList(List<AllowUploadType> allowUploadTypeList) {
		this.allowUploadTypeList = allowUploadTypeList;
	}
	public UploadOpenService getUploadOpenService() {
		return uploadOpenService;
	}
	public void setUploadOpenService(UploadOpenService uploadOpenService) {
		this.uploadOpenService = uploadOpenService;
	}
	public WatermarkPostion getWatermarkPostion() {
		return watermarkPostion;
	}
	public void setWatermarkPostion(WatermarkPostion watermarkPostion) {
		this.watermarkPostion = watermarkPostion;
	}
	public String getApiClientNo() {
		return apiClientNo;
	}
	public void setApiClientNo(String apiClientNo) {
		this.apiClientNo = apiClientNo;
	}
	
}
